import { defineStore } from "pinia";
import _hook from "@/hooks/use/index.js";
import { login, getUserInfo } from "@/api/user.js";
import { reactive, ref } from "vue";

export const useUser = defineStore("useUser", () => {
  const userInfo = ref({})
  const token = ref(_hook.useSessionStorage.get("token") || "")

  // 设置用户信息
  const setUserInfo = async () => {
    if (_hook.useSessionStorage.get("userInfo")) {
      userInfo.value = _hook.useSessionStorage.get("userInfo");
    } else {
      userInfo.value = await this.getUserInfo();
    }
  }
  // 登录
  const userlogin = (param) => {
    return login(param).then((res) => {
      userInfo.value = res.userInfo;
      _hook.useSessionStorage.set("token", res.userInfo.token);
      _hook.useSessionStorage.set("userInfo", userInfo.value);
      return userInfo.value;
    });
  }
  // 获取用户信息
  const getUserInfoData = () => {
    return getUserInfo().then((res) => {
      return res.userInfo;
    });
  }
  return {
    userInfo,
    token,
    setUserInfo,
    userlogin,
    getUserInfoData
  }
});
